<template>
    <div class="count-box">
        <button @click="handleSub" class="sub" >-</button>
        <input class="inp" @change="handleChange" :value="value" type="text">
        <button @click="handleAdd" class="add">+</button>
    </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      default: 1
    },
    goodsId: {
      type: Number
    }
  },
  methods: {
    handleSub () {
      if (this.value <= 1) {
        return
      }
      this.$emit('input', this.value - 1)
    },
    handleAdd () {
      this.$emit('input', this.value + 1)
    },
    handleChange (e) {
      const num = +e.target.value
      // 输入了不合法文本 或者 输入了负数，回退成原来的 valu 值
      if (isNaN(num) || num <= 0) {
        e.target.value = this.value
        return
      }
      this.$emit('input', num)
    }
  }
}
</script>

<style lang="less" scoped>
.count-box{
    width: 110px;
    display: flex;
    justify-content: space-between;
    .add, .sub{
        width: 30px;
        height: 30px;
        border: none;
        outline: none;
        background-color: #efefef;
    }
    .inp{
        width: 40px;
        height: 30px;
        border: none;
        outline: none;
        background-color: #efefef;
        line-height: 30px;
        text-align: center;
    }
}
</style>
